import { ContextMenu } from "@renderer/components/ui/base/context-menu";
import { TextField } from "@renderer/components/ui/base/text-field";
import logger from "@renderer/config/logger";
import {
  type MenuModelActionType,
  useThreadMenu,
} from "@renderer/hooks/use-thread-menu";
import { cn } from "@renderer/lib/utils";
import { useMessagesLengthByThread } from "@renderer/queries";
import type { Thread } from "@shared/triplit/types";
import {
  Eraser,
  FileText,
  FolderX,
  Package,
  Pencil,
  Trash2,
} from "lucide-react";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { ActionGroup } from "../action-group";
import { ModalAction } from "../modal-action";

interface ThreadMenuProps {
  thread: Thread;
  isCurrent: boolean;
  displayTrigger?: "hover" | "always";
}
const { threadService } = window.service;

export function ThreadMenu({
  thread,
  isCurrent,
  displayTrigger = "hover",
}: ThreadMenuProps) {
  const { t } = useTranslation();
  const { data: messagesLength } = useMessagesLengthByThread(thread.id);

  const {
    state,
    newTitle,
    formattedTitle,
    setState,
    setNewTitle,
    closeModal,

    handleRename,
    handleCleanMessages,
    handleDelete,
    handleCollectThread,
    handleDeleteAll,
  } = useThreadMenu(thread);

  // Memoize action configurations to avoid recreating objects on every render
  const actionConfigs = useMemo(
    () => ({
      rename: {
        title: t("thread-menu.actions.rename.title"),
        descriptions: [t("thread-menu.actions.rename.description")],
        confirmText: t("thread-menu.actions.rename.confirmText"),
        action: async () => await handleRename(),
      },
      "clean-messages": {
        title: t("thread-menu.actions.clean-messages.title"),
        descriptions: [t("thread-menu.actions.clean-messages.description")],
        confirmText: t("thread-menu.actions.clean-messages.confirmText"),
        action: async () => await handleCleanMessages(),
      },
      delete: {
        title: t("thread-menu.actions.delete.title"),
        descriptions: [t("thread-menu.actions.delete.description")],
        confirmText: t("thread-menu.actions.delete.confirmText"),
        action: async () => await handleDelete(),
      },
      "delete-all": {
        title: t("thread-menu.actions.delete-all.title"),
        descriptions: [t("thread-menu.actions.delete-all.description")],
        confirmText: t("thread-menu.actions.delete-all.confirmText"),
        action: async () => await handleDeleteAll(),
      },
    }),
    [t, handleRename, handleCleanMessages, handleDelete, handleDeleteAll],
  );

  const actionType = (action: MenuModelActionType | null) => {
    const initialsState = {
      title: "",
      descriptions: [""],
      confirmText: "",
      action: () => {},
    };

    if (!action || !(action in actionConfigs)) {
      return initialsState;
    }

    const config = actionConfigs[action as keyof typeof actionConfigs];

    // Special handling for rename action with dynamic body and disabled state
    if (action === "rename") {
      return {
        ...config,
        body: (
          <TextField
            aria-label={`Rename thread ${thread.title}`}
            value={newTitle}
            onChange={setNewTitle}
            autoFocus
            placeholder={t("thread-menu.actions.rename.edit.placeholder")}
          />
        ),
        disabled: formattedTitle.length === 0,
      };
    }

    return config;
  };

  const handleGenerateTitle = async () => {
    const { isOk, errorMsg } = await threadService.summaryTitle(thread.id);

    if (!isOk) {
      toast.error(t("thread-menu.actions.generate-title.error"));
      logger.error("ThreadMenu:handleGenerateTitle error", {
        errorMsg,
      });
    }
  };

  return (
    <div className="w-full">
      <ContextMenu>
        <ContextMenu.Trigger
          className="relative w-full cursor-pointer truncate py-1.5 pr-7 text-left"
          title={thread.title}
          onDoubleClick={() => setState("rename")}
        >
          {thread.title}
        </ContextMenu.Trigger>

        <ActionGroup
          onStar={handleCollectThread}
          stared={thread.collected}
          className={cn(
            "-translate-y-1/2 absolute top-1/2 right-3 opacity-0 transition-opacity group-hover:opacity-100",
            displayTrigger === "always" && "opacity-100",
          )}
          starTooltip={
            thread.collected
              ? t("sidebar.menu-item.uncollect-thread")
              : t("sidebar.menu-item.collect-thread")
          }
          isCurrent={isCurrent}
        />

        <ContextMenu.Content aria-label={`Thread options for ${thread.title}`}>
          <ContextMenu.Item onAction={() => setState("rename")}>
            <Pencil className="mr-2 h-4 w-4" />
            {t("sidebar.menu-item.rename")}
          </ContextMenu.Item>
          <ContextMenu.Item
            onAction={handleGenerateTitle}
            isDisabled={messagesLength === 0}
          >
            <FileText className="mr-2 h-4 w-4" />
            {t("sidebar.menu-item.generate-title")}
          </ContextMenu.Item>
          <ContextMenu.Item onAction={() => setState("clean-messages")}>
            <Eraser className="mr-2 h-4 w-4" />
            {t("sidebar.menu-item.clean-messages")}
          </ContextMenu.Item>
          <ContextMenu.Item onAction={handleCollectThread}>
            <Package className="mr-2 h-4 w-4" />
            {thread.collected
              ? t("sidebar.menu-item.uncollect-thread")
              : t("sidebar.menu-item.collect-thread")}
          </ContextMenu.Item>
          <ContextMenu.Separator />
          <ContextMenu.Item isDanger={true} onAction={() => setState("delete")}>
            <Trash2 className="mr-2 h-4 w-4" />
            {t("sidebar.menu-item.delete")}
          </ContextMenu.Item>
          <ContextMenu.Item
            isDanger={true}
            onAction={() => setState("delete-all")}
          >
            <FolderX className="mr-2 h-4 w-4 stroke-2" />
            {t("sidebar.menu-item.delete-all")}
          </ContextMenu.Item>
        </ContextMenu.Content>
      </ContextMenu>

      <ModalAction
        state={state}
        onOpenChange={closeModal}
        actionType={actionType(state)}
      />
    </div>
  );
}
